package com.eastseeway.radioproject.base;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.eastseeway.commonlib_esw.utils.SoundPoolUtil;
import com.eastseeway.radioproject.RadioApplication;
import com.eastseeway.radioproject.utils.SPHelper;

import org.greenrobot.eventbus.EventBus;

public abstract class BaseActivity<T extends ViewDataBinding,VM extends BaseViewModel> extends AppCompatActivity {

    protected VM mViewModel;

    protected T mBinding;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, getLayoutId());
        mViewModel = new ViewModelProvider(this).get(getVMClass());
        mBinding.setLifecycleOwner(this);
        if (isRegisterEventbus()) {
            EventBus.getDefault().register(this);
        }
        //        设置相关事件
        initEvent();
//        开始加载数据
        loadData();
//        观察数据
        observeData();
    }

//    是否注册eventbus 如果不需要注册可以重写这个方法返回false，默认返回true，需要复写@Subscribe(threadMode = ThreadMode.MAIN)
    protected boolean isRegisterEventbus(){
        return true;
    }

//    设置布局文件 R.layout.***
    protected abstract int getLayoutId();

    protected void observeData() {}

    protected void loadData() {}

    protected void initEvent(){}

//    获取viewmodel的class
    protected abstract Class<VM> getVMClass();
//    播放点击音效
    protected void playClickSound(){
        SoundPoolUtil.getInstance().play("click",0);
    }

    protected void playExceptionSound(int position){
//        6 1;7 2
        SoundPoolUtil.getInstance().play("bit_"+position,0);
    }

    protected void playInstallElectrodeSound(){
        SoundPoolUtil.getInstance().play("install_electrode",0);
    }

    protected void playSound(String soundName){
        SoundPoolUtil.getInstance().play(soundName,0);
    }

    protected boolean isTcpConnected() {
        return SPHelper.getTcpConnectStatus(this);
    }

    /**
    * 获取设备类型
    * @return 设备类型
    * {@link Const#MACHINE_TYPE_TAISHI}
    * {@link Const#MACHINE_TYPE_LISHI}
    */
    public String getMachineType(Context context) {
        return SPHelper.getMachineType(context);
    }

    protected void sendMessage(byte[] msg) {
        RadioApplication.getInstance().sendData(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isRegisterEventbus()) {
            EventBus.getDefault().unregister(this);
        }
    }
}
